import { ajaxAsync } from 'vue-xiaobu-utils'
import { isUserLogin } from '../../../utils/UserBeanUtils'

const NOT_LOGIN = -1 // 未登陆
const CARD_NOT_OPEN = 0 // 未开通
const CARD_IS_APPLYING = 1 // 正在审核
const CARD_OPEN = 2 // 已开通
const CARD_FREEZON = 3 // 已冻结

async function getBusCardInfo() {
  return new Promise((resolve, reject) => {
    if (isUserLogin()) {
      ajaxAsync('/vcard/info/list', {}, 2)
        .then(res => {
          let list = res.LIST
          let busCard = list.find(
            card => card.CARD_INSTANCE_ID === 'jhx_buscard'
          )
          if (busCard) {
            let status = busCard.STATE
            if (status === CARD_OPEN || status === CARD_FREEZON) {
              resolve(busCard)
            } else {
              reject(new Error(status))
            }
          } else {
            reject(new Error(CARD_NOT_OPEN))
          }
        })
        .catch(err => {
          let code = err.error.response.status
          if (code === 403) reject(new Error(NOT_LOGIN))
        })
    } else {
      reject(new Error(NOT_LOGIN))
    }
  })
}

async function getUnReadMessageCount() {
  if (isUserLogin()) {
    try {
      let res = await ajaxAsync('/user/message/unread_count', {}, 2)
      return res.COUNT
    } catch (err) {
      let code = err.error.response.status
      if (code === 403) return 0
    }
  } else {
    return 0
  }
}

export {
  getBusCardInfo,
  getUnReadMessageCount,
  NOT_LOGIN,
  CARD_NOT_OPEN,
  CARD_FREEZON,
  CARD_IS_APPLYING,
  CARD_OPEN
}
